package com.yue.ssa.config;

import com.yue.ssa.bean.User;
import com.yue.ssa.common.Constant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class MyAuthenticationProvider extends DaoAuthenticationProvider {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //使用邮箱认证 短信认证同理
        String sms = req.getParameter("sms");
        if (StringUtils.isNotBlank(sms)) {
            User user = (User) userDetails;
            //验证码登录
            if (!sms.equals(redisTemplate.opsForValue().get(user.getEmail()))) {
                throw new AuthenticationServiceException(Constant.VERIFICATION_CODE_ERROR);
            }
        } else {
            String code = req.getParameter("code");
            String verify_code = (String) req.getSession().getAttribute("verify_code");
            if (code == null || verify_code == null || !code.equalsIgnoreCase(verify_code)) {
                throw new AuthenticationServiceException(Constant.VERIFICATION_CODE_ERROR);
            }
            //密码验证
            super.additionalAuthenticationChecks(userDetails, authentication);
        }
    }
}